//
//  YAYIPhotoItemController.m
//  图片多选
//
//  Created by hxp on 16/6/27.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIPhotoItemController.h"
#import "ELNALAsset.h"
#import "YAYIPhotoItemCell.h"
@interface YAYIPhotoItemController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *selectedAssetsGroupImages;
@property (nonatomic,strong)UIButton *backBtn;
@end

@implementation YAYIPhotoItemController
static NSString * const reuseIdentifier = @"Cell";
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择图片";
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    if (!_selectedAssetsGroupImages) {
        _selectedAssetsGroupImages = [NSMutableArray array];
    }
    [self rightBtn];
    [self getAllPhotos];
    [self createcollectionView];
    [self createBackButton];
}
-(void)rightBtn{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"完成" forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 40, 40);
    [button addTarget:self action:@selector(finishedAction:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = item;
    
}
-(void)finishedAction:(UIButton *)sender
{
    UIViewController *view = self.navigationController.viewControllers[0];
    [self.navigationController popToViewController:view animated:YES];
    if (_delegate && [_delegate respondsToSelector:@selector(imageAry:)]) {
        [_delegate imageAry:_selectedAssetsGroupImages];
    }
    [view dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)getAllPhotos{
    if (!_selectedAssetsGroup) {
        _selectedAssetsGroup = [[ALAssetsGroup alloc] init];
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [_selectedAssetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            if (result) {
                ELNALAsset *asset = [[ELNALAsset alloc]init];
                asset.asset = result;
                asset.isSelected = NO;
                [_dataSource addObject:asset];
            }
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
            long section = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
            long row = [self collectionView:self.collectionView numberOfItemsInSection:section] - 1;
            if (section >= 0 && row >= 0) {
                NSIndexPath *ip = [NSIndexPath indexPathForRow:row
                                                     inSection:section];
                [self.collectionView scrollToItemAtIndexPath:ip atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
            }
        });
    });
    
    
}

-(void)createcollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height ) collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: self.collectionView];
    [self.collectionView registerClass:[YAYIPhotoItemCell class] forCellWithReuseIdentifier:reuseIdentifier];
}
#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YAYIPhotoItemCell *cell = (YAYIPhotoItemCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    ELNALAsset *asset = self.dataSource[indexPath.row];
    cell.photo.clipsToBounds = YES;
    cell.photo.contentMode = UIViewContentModeScaleAspectFill;
    cell.photo.image = [UIImage imageWithCGImage:asset.asset.aspectRatioThumbnail];
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CGSizeMake((100/320.0)*SCREEN_width, (100/320.0)*SCREEN_width);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5.f;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //调用方法修改cell的选中状态
    [self changeCellWithIndexPath:indexPath];
}
//替选
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    //调用方法修改cell的选中状态
    //[self changeCellWithIndexPath:indexPath];
}
#pragma mark -- 修改cell的状态
- (void)changeCellWithIndexPath:(NSIndexPath *)indexPath{
    //1.通过indexPath获取到数据源中的模型对象，修改对象中修改状态
    ELNALAsset *asset = _dataSource[indexPath.row];
    asset.isSelected ^= 1;
    [_dataSource replaceObjectAtIndex:indexPath.row withObject:asset];
    //2.将数据模型添加或者移除
    //如果选中将数据模型加入选中的数组
    CGImageRef ref = [[asset.asset  defaultRepresentation] fullResolutionImage];
    UIImage *img = [[UIImage alloc]initWithCGImage:ref];
    if (asset.isSelected) {
        [self.selectedAssetsGroupImages addObject:img];
    }else{
        //如果取消选中将数据模型从选中数组中移除
        [self.selectedAssetsGroupImages removeObject:img];
    }
    //3，修改cell上显示的选中图片的显示状态
    YAYIPhotoItemCell *cell = (YAYIPhotoItemCell *)[_collectionView cellForItemAtIndexPath:indexPath];
    [cell changeSelectedWithALAsset:asset];
}
/** 创建返回按钮
 *
 */
-(void)createBackButton{
    if (self.backBtn == nil) {
        
        self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.backBtn setImage:[UIImage  imageNamed:@"back_button"] forState:UIControlStateNormal];
        self.backBtn.frame = CGRectMake(0, 0, 70, 20);
        self.backBtn.contentMode = UIViewContentModeLeft;
        self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *item = [[UIBarButtonItem  alloc] initWithCustomView:self.backBtn];
        self.navigationItem.leftBarButtonItem = item;
    }
}
-(void)backAction:(UIButton *)sender
{
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
@end
